from func import Func
import time
import pymongo
import redis_


class MongoListener:
    def __init__(self, mongo_client, redis_client):
        self.mongo_client = mongo_client
        self.client = mongo_client.client
        self.id_pools = mongo_client.id_pools
        self.acv_log = self.client.guidang4.addacvs_img
        self.capture = self.client.guidang4.capture
        self.insert_fail = mongo_client.insert_fail
        self.run11 = self.client.guidang4.RUN11

        self.func_client = mongo_client.func_client_A
        self.box_ip_D = mongo_client.box_ip_D
        # self.box_ip_A = mongo_client.box_ip_A

        self.redis_client = redis_client

    def mongo_listen(self, sleep_time):
        # 按时间戳 顺序读取
        results = self.acv_log.find({'hezi_guidang_ip': self.box_ip_D})
        for result in results:
            face_id = result.get("_id")
            feature = result.get("ovn_f")
            hezi_face_id = self.id_pools.find_one_and_update({'_id': "idpools"}, {"$inc": {"face_id": 1}}, upsert=True)[
                "face_id"]

            repo_id, repo_id_key = self.mongo_client.get_current_use_repo('A')
            # 插入动态库
            ins_result = self.func_client.insert_feature(repo_id, hezi_face_id, feature, face_id)

            if ins_result.get("message") != "success":
                data_dic = {
                    "hezi_guidang_repo_id": '%s' % repo_id,
                    "face_id": face_id,
                    "hezi_face_id": hezi_face_id,
                    "timestamp": result.get("timestamp"),
                    "hezi_guidang_ip": result.get("hezi_guidang_ip")
                }

                self.insert_fail.insert_one(data_dic)
                raise Exception(ins_result.get("message"))
            # 动态库增值
            self.mongo_client.inc_count(repo_id_key, "A")

            self.run11.insert_one(result)

            self.clear_handled(face_id)
            # 升级 hezi_face_id
            self.capture.update_one({"_id": face_id}, {'$set': {'hezi_face_id': hezi_face_id}}, upsert=True)
            self.redis_client.insert_specific_data(face_id, 'hezi_face_id', hezi_face_id)

        time.sleep(sleep_time)

    # def get_stranger_repos(self):
    #     results = list(self.pools.find({"hezi_guidang_repo_id": {"$exists": True}}))
    #     repos = []
    #     for item in results:
    #         repos.append(int(item.get("hezi_guidang_repo_id")))
    #     return repos

    def clear_handled(self, face_id):
        self.acv_log.delete_one({"_id": str(face_id)})


def loops(mongo_client, redis_client, sleep_time):
    while True:
        try:
            ml = MongoListener(mongo_client, redis_client)
            while True:
                ml.mongo_listen(sleep_time)
        except Exception as e:
            print(e)
            time.sleep(5)
